package com.gxa.employment.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gxa.employment.entity.dto.ReallocatePermDto;
import com.gxa.employment.entity.pojo.Permission;
import com.gxa.employment.entity.pojo.Role;
import com.gxa.employment.entity.vo.ListsVo;
import com.gxa.employment.exception.BizException;
import com.gxa.employment.exception.ErrorMessage;
import com.gxa.employment.mapper.RoleMapper;
import com.gxa.employment.service.PermissionService;
import com.gxa.employment.service.RoleService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * <p>
 * 系统角色表 服务实现类
 * </p>
 *
 * @author author
 * @since 2025-03-25
 */
@Service
@Transactional(rollbackFor = Throwable.class)
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements RoleService {


    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private PermissionService permissionService;

    @Autowired
    RedisTemplate<String, Object> redisTemplate;

    /**
     * 重新分配菜单
     *
     * @param dto 包含菜单ID列表和角色ID的数据传输对象
     * @throws BizException 如果输入数据无效，将抛出业务异常
     */
    @Override
    public void reallocatePerm(ReallocatePermDto dto) throws BizException {
        if (dto == null) {
            throw new BizException(ErrorMessage.INPUT_EMPTY);
        }
        Integer roleId = dto.getRoleId();
        //删除该角色特定的权限
        roleMapper.deletePermByType(roleId, dto.getType());
        //为该角色添加分配权限
        roleMapper.insertAll(dto.getPermIds(), roleId);
        //删除redis的缓存
      //  redisTemplate.delete("role:"+roleId);
    }

    /**
     * 获取所有列表信息
     *
     * @return 包含角色列表、菜单权限列表和API权限列表的ListsVo对象
     */
    @Override
    public ListsVo getAllList() {
        List<Permission> menuList = permissionService.getAllPermission("菜单");
        List<Permission> buttonList = permissionService.getAllPermission("按钮");
        List<Permission> permissionList = permissionService.getAllPermission("API");
        return new ListsVo(list(),menuList,buttonList,permissionList);
    }

    @Override
    public List<Integer> getByRole(Integer roleId,String type) {
        return roleMapper.selectByRole(roleId,type);
    }

}
